package com.yoyo.yyadsdk.serv;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import com.yoyo.ad.contract.AdContract;
import com.yoyo.ad.main.IAdFactory;
import com.yoyo.ad.main.YoYoAdManager;
import com.yoyo.yyadsdk.bean.dao.AdvScreenEntity;
import com.yoyo.yyadsdk.util.AdvUtils;
import com.yoyo.yyadsdk.util.TimeUtils;

public abstract class WindowBaseService extends Service implements AdContract.View {

    protected static final String TAG = "WindowBaseService";
    protected int mWidth;
    protected int mHeight;

    private WindowManager wManager;// 窗口管理者
    protected WindowManager.LayoutParams mParams;// 窗口的属性
    private View inflate;

    private boolean flag = true;
    private String mAty;
    private AdvScreenEntity mAdv;
    protected IAdFactory mAdFactory;
    private Handler mHandler = new Handler();
    private Runnable mRunnable;

    protected abstract int getLayoutId();

    protected abstract void initStyle(WindowManager.LayoutParams params);

    protected abstract int getAdvType();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        wManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        mParams = new WindowManager.LayoutParams();
        mParams.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;// 系统提示window TYPE_SYSTEM_ALERT  /  锁屏TYPE_SYSTEM_ERROR
        mParams.format = PixelFormat.TRANSLUCENT;// 支持透明
        mParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;// 焦点
        DisplayMetrics outMetrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wManager.getDefaultDisplay().getRealMetrics(outMetrics);
        } else {
            wManager.getDefaultDisplay().getMetrics(outMetrics);
        }
        mWidth = outMetrics.widthPixels;
        mHeight = outMetrics.heightPixels;
        //mParams.format = PixelFormat.RGBA_8888;
        initStyle(mParams);
        //mParams.alpha = 0.1f;//窗口的透明度

        inflate = LayoutInflater.from(this).inflate(getLayoutId(), null);
        initInflate(inflate);
        registerBroadcast();
        super.onCreate();
    }

    protected abstract void initInflate(View inflate);

    protected abstract void initData();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (flag) {
            flag = false;
            mAty = intent.getStringExtra("aty");
            mAdv = intent.getParcelableExtra("adv");
            YoYoAdManager.getConfig(this, this);
            initData();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    protected void show(){
        wManager.addView(inflate, mParams);//添加窗口
    }

    protected void loadSuccess() {
        wManager.addView(inflate, mParams);//添加窗口
        long duration = mAdv.getDuration();
        //记录本地数据
        AdvUtils.recordAdvExposed(mAdv.getId(), getAdvType());
        //延时关闭
        if (duration > 0) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    stopSelf();
                }
            }, duration * TimeUtils.SECOND);
            mRunnable = new Runnable() {
                @Override
                public void run() {
                    stopSelf();
                }
            };
            mHandler.postDelayed(mRunnable, duration * TimeUtils.SECOND);
        }
    }

    protected void loadFail() {
        //记录本地数据
        AdvUtils.recordAdvExposed(mAdv.getId(), getAdvType());
    }

    @Override
    public void onDestroy() {
        if (inflate.getParent() != null)
            wManager.removeView(inflate);//移除窗口
        unregisterReceiver(mDismissReceiver);
        if (mAdFactory != null)
            mAdFactory.destroy();
        if (mHandler != null) {
            if (mRunnable != null) {
                mHandler.removeCallbacks(mRunnable);
                mRunnable = null;
            }
            mHandler = null;
        }
        super.onDestroy();
    }

    private DismissReceiver mDismissReceiver;

    private void registerBroadcast() {
        //注册接收异常广播消息
        mDismissReceiver = new DismissReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(com.yoyo.yyadsdk.broad.DismissReceiver.ACTION);
        registerReceiver(mDismissReceiver, filter);
    }

    @Override
    public void onAdFail(String err) {
        Log.e(TAG, err);
        stopSelf();
    }

    public class DismissReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && com.yoyo.yyadsdk.broad.DismissReceiver.ACTION.equals(intent.getAction())) {
                String aty = intent.getStringExtra("aty");
                if (!aty.equals(mAty)) {
                    stopSelf();
                }
            }
        }
    }
}
